package com.jn.zhinongbao.adapter.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.example.supportingagriculturaltreasures.OrderActivity;
import com.example.supportingagriculturaltreasures.R;
import com.example.supportingagriculturaltreasures.bean.Order;

import java.util.List;

public class OrderAdapter extends RecyclerView.Adapter<OrderAdapter.OrderViewHolder> {

    private Context context;
    private List<Order> orderList;
    private OnOrderItemClickListener listener;

    public interface OnOrderItemClickListener {
        void onOrderClick(Order order);
        void onOrderStatusChange(Order order, int newStatus);
    }

    public OrderAdapter(Context context, List<Order> orderList, OnOrderItemClickListener listener) {
        this.context = context;
        this.orderList = orderList;
        this.listener = listener;
    }

    @NonNull
    @Override
    public OrderViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.item_order, parent, false);
        return new OrderViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull OrderViewHolder holder, int position) {
        Order order = orderList.get(position);
        
        holder.tvOrderId.setText("订单号: " + order.getId());
        holder.tvProductName.setText(order.getProductName());
        holder.tvProductPrice.setText("¥" + String.format("%.2f", order.getProductPrice()));
        holder.tvQuantity.setText("x" + order.getQuantity());
        holder.tvTotalAmount.setText("¥" + String.format("%.2f", order.getTotalAmount()));
        holder.tvOrderStatus.setText(getStatusText(order.getStatus()));
        holder.tvCreateTime.setText(order.getCreateTime());
        holder.tvShippingAddress.setText("收货地址: " + order.getShippingAddress());
        holder.tvContactPhone.setText("联系电话: " + order.getContactPhone());
        
        // 设置状态颜色
        holder.tvOrderStatus.setTextColor(getStatusColor(order.getStatus()));
        
        // 使用Glide加载商品图片
        loadProductImage(holder.ivProductImage, order.getProductImageUrl());

        // 根据订单状态设置可用的操作按钮
        setupActionButtons(holder, order);

        // 整个item点击
        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onOrderClick(order);
            }
        });
    }

    private void setupActionButtons(OrderViewHolder holder, Order order) {
        holder.btnAction1.setVisibility(View.GONE);
        holder.btnAction2.setVisibility(View.GONE);

        switch (order.getStatus()) {
            case OrderActivity.STATUS_PAID:
                // 已付款 - 可以取消订单
                holder.btnAction1.setVisibility(View.VISIBLE);
                holder.btnAction1.setText("取消订单");
                holder.btnAction1.setOnClickListener(v -> {
                    if (listener != null) {
                        listener.onOrderStatusChange(order, OrderActivity.STATUS_CANCELLED);
                    }
                });
                break;
                
            case OrderActivity.STATUS_PENDING:
                // 待发货 - 可以取消订单
                holder.btnAction1.setVisibility(View.VISIBLE);
                holder.btnAction1.setText("取消订单");
                holder.btnAction1.setOnClickListener(v -> {
                    if (listener != null) {
                        listener.onOrderStatusChange(order, OrderActivity.STATUS_CANCELLED);
                    }
                });
                break;
                
            case OrderActivity.STATUS_SHIPPED:
                // 已发货 - 可以确认收货
                holder.btnAction1.setVisibility(View.VISIBLE);
                holder.btnAction1.setText("确认收货");
                holder.btnAction1.setOnClickListener(v -> {
                    if (listener != null) {
                        listener.onOrderStatusChange(order, OrderActivity.STATUS_CONFIRMED);
                    }
                });
                break;
                
            case OrderActivity.STATUS_CONFIRMED:
                // 确认收货 - 可以评价（这里简化处理）
                holder.btnAction1.setVisibility(View.VISIBLE);
                holder.btnAction1.setText("评价");
                holder.btnAction1.setOnClickListener(v -> {
                    // TODO: 跳转到评价页面
                });
                break;
                
            case OrderActivity.STATUS_CANCELLED:
                // 已取消 - 可以删除订单
                holder.btnAction1.setVisibility(View.VISIBLE);
                holder.btnAction1.setText("删除订单");
                holder.btnAction1.setOnClickListener(v -> {
                    if (listener != null) {
                        // 使用特殊状态 -999 表示删除订单
                        listener.onOrderStatusChange(order, -999);
                    }
                });
                break;
        }
    }

    private String getStatusText(int status) {
        switch (status) {
            case OrderActivity.STATUS_PAID:
                return "已付款";
            case OrderActivity.STATUS_PENDING:
                return "待发货";
            case OrderActivity.STATUS_SHIPPED:
                return "已发货";
            case OrderActivity.STATUS_CONFIRMED:
                return "确认收货";
            case OrderActivity.STATUS_CANCELLED:
                return "已取消";
            default:
                return "未知状态";
        }
    }

    private int getStatusColor(int status) {
        switch (status) {
            case OrderActivity.STATUS_PAID:
                return 0xFF4CAF50; // 绿色
            case OrderActivity.STATUS_PENDING:
                return 0xFFFF9800; // 橙色
            case OrderActivity.STATUS_SHIPPED:
                return 0xFF2196F3; // 蓝色
            case OrderActivity.STATUS_CONFIRMED:
                return 0xFF4CAF50; // 绿色
            case OrderActivity.STATUS_CANCELLED:
                return 0xFFF44336; // 红色
            default:
                return 0xFF666666; // 灰色
        }
    }

    @Override
    public int getItemCount() {
        return orderList.size();
    }

    /**
     * 使用Glide加载商品图片
     */
    private void loadProductImage(ImageView imageView, String imageUrl) {
        RequestOptions options = new RequestOptions()
                .placeholder(R.drawable.ic_launcher_foreground) // 加载中显示的图片
                .error(R.drawable.ic_launcher_foreground) // 加载失败显示的图片
                .transform(new RoundedCorners(12)); // 圆角处理

        if (imageUrl != null && !imageUrl.isEmpty()) {
            Glide.with(context)
                    .load(imageUrl)
                    .apply(options)
                    .into(imageView);
        } else {
            // 如果没有图片URL，显示默认图片
            imageView.setImageResource(R.drawable.ic_launcher_foreground);
        }
    }

    static class OrderViewHolder extends RecyclerView.ViewHolder {
        TextView tvOrderId;
        ImageView ivProductImage;
        TextView tvProductName;
        TextView tvProductPrice;
        TextView tvQuantity;
        TextView tvTotalAmount;
        TextView tvOrderStatus;
        TextView tvCreateTime;
        TextView tvShippingAddress;
        TextView tvContactPhone;
        Button btnAction1;
        Button btnAction2;

        public OrderViewHolder(@NonNull View itemView) {
            super(itemView);
            tvOrderId = itemView.findViewById(R.id.tv_order_id);
            ivProductImage = itemView.findViewById(R.id.iv_product_image);
            tvProductName = itemView.findViewById(R.id.tv_product_name);
            tvProductPrice = itemView.findViewById(R.id.tv_product_price);
            tvQuantity = itemView.findViewById(R.id.tv_quantity);
            tvTotalAmount = itemView.findViewById(R.id.tv_total_amount);
            tvOrderStatus = itemView.findViewById(R.id.tv_order_status);
            tvCreateTime = itemView.findViewById(R.id.tv_create_time);
            tvShippingAddress = itemView.findViewById(R.id.tv_shipping_address);
            tvContactPhone = itemView.findViewById(R.id.tv_contact_phone);
            btnAction1 = itemView.findViewById(R.id.btn_action1);
            btnAction2 = itemView.findViewById(R.id.btn_action2);
        }
    }
} 